from app.schemas.advertisement import AdvertisementCreate, AdvertisementUpdate, Advertisement
from app.database.connection import get_database
from datetime import datetime
from bson import ObjectId

async def create_advertisement(ad: AdvertisementCreate) -> Advertisement:
    """创建广告"""
    db = get_database()
    
    # 创建广告文档
    ad_dict = ad.dict()
    ad_dict["advertiser_id"] = ObjectId(ad_dict["advertiser_id"])
    ad_dict["created_at"] = datetime.utcnow()
    ad_dict["click_count"] = 0
    ad_dict["impression_count"] = 0
    
    # 插入数据库
    result = await db["advertisements"].insert_one(ad_dict)
    
    # 获取创建的广告
    created_ad = await db["advertisements"].find_one({"_id": result.inserted_id})
    
    # 转换为Advertisement对象
    ad_response = created_ad.copy()
    ad_response["id"] = str(ad_response["_id"])
    ad_response["advertiser_id"] = str(ad_response["advertiser_id"])
    
    return Advertisement(**ad_response)

async def get_advertisements(skip: int = 0, limit: int = 100) -> list[Advertisement]:
    """获取广告列表"""
    db = get_database()
    ads_cursor = db["advertisements"].find().skip(skip).limit(limit)
    ads = await ads_cursor.to_list(length=limit)
    
    result = []
    for ad_doc in ads:
        ad_response = ad_doc.copy()
        ad_response["id"] = str(ad_response["_id"])
        ad_response["advertiser_id"] = str(ad_response["advertiser_id"])
        result.append(Advertisement(**ad_response))
    
    return result

async def get_advertisement(ad_id: str) -> Advertisement:
    """获取广告详情"""
    db = get_database()
    try:
        ad_doc = await db["advertisements"].find_one({"_id": ObjectId(ad_id)})
        if ad_doc:
            ad_response = ad_doc.copy()
            ad_response["id"] = str(ad_response["_id"])
            ad_response["advertiser_id"] = str(ad_response["advertiser_id"])
            return Advertisement(**ad_response)
        return None
    except Exception:
        return None

async def update_advertisement(ad_id: str, ad_update: AdvertisementUpdate) -> Advertisement:
    """更新广告"""
    db = get_database()
    
    # 构建更新字典
    update_data = {k: v for k, v in ad_update.dict().items() if v is not None}
    if not update_data:
        return await get_advertisement(ad_id)
    
    # 更新数据库
    result = await db["advertisements"].update_one(
        {"_id": ObjectId(ad_id)},
        {"$set": update_data}
    )
    
    if result.modified_count == 0:
        return None
    
    return await get_advertisement(ad_id)

async def delete_advertisement(ad_id: str) -> bool:
    """删除广告"""
    db = get_database()
    result = await db["advertisements"].delete_one({"_id": ObjectId(ad_id)})
    return result.deleted_count > 0

async def increment_ad_click_count(ad_id: str) -> bool:
    """增加广告点击数"""
    db = get_database()
    result = await db["advertisements"].update_one(
        {"_id": ObjectId(ad_id)},
        {"$inc": {"click_count": 1}}
    )
    return result.modified_count > 0

async def increment_ad_impression_count(ad_id: str) -> bool:
    """增加广告展示数"""
    db = get_database()
    result = await db["advertisements"].update_one(
        {"_id": ObjectId(ad_id)},
        {"$inc": {"impression_count": 1}}
    )
    return result.modified_count > 0